
package com.xpo.settingskeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.Intent;
import android.content.res.XmlResourceParser;
import android.util.Log;

public class Utility {
    private static final String TAG = "Utility";

    public static final String ATTR_NAME = "name";

    public static final String TAG_NAME = "settings";

    static public void startBackupServcie(Context context) {
        Log.i(TAG, "startBackupServcie()");

        try {
            Intent backupIntent = new Intent();
            backupIntent.setClass(context, BackupService.class);
            backupIntent.setAction(NameSpace.BACKUP_SERVICE);
            context.startService(backupIntent);
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

    static public void startBackupService() {
        Log.i(TAG, "startBackupService()");
    }

    /**
     * read setting name list from resource
     * 
     * @return list of setting name
     */
    public static ArrayList<String> getSettingNameList(int resource, Context context) {
        XmlResourceParser parser = context.getResources().getXml(resource);
        ArrayList<String> settingNameList = new ArrayList<String>();

        try {
            while (parser.next() != XmlPullParser.END_DOCUMENT) {
                if (parser.getEventType() == XmlPullParser.START_TAG
                        && TAG_NAME.equals(parser.getName())) {
                    String settingName = parser.getAttributeValue(null, ATTR_NAME);
                    if (settingName != null) {
                        Log.i(TAG, settingName);
                        settingNameList.add(settingName);
                    }
                }
            }
        } catch (XmlPullParserException e) {
            Log.e(TAG, "Parser Exception : ", e);
        } catch (IOException e) {
            Log.e(TAG, "IOException : ", e);
        }

        parser.close();

        return settingNameList;
    }

    static public String genDbName() {
        Calendar rightNow = Calendar.getInstance();
        Date date = new Date();
        String dbName = String.format("%04d.%02d.%02d-%02d.%02d.%02d", rightNow.get(Calendar.YEAR),
                rightNow.get(Calendar.MONTH), rightNow.get(Calendar.DAY_OF_MONTH), date.getHours(),
                date.getMinutes(), date.getSeconds());
        dbName += ".db";
        return dbName;
    }
}
